package cn.dianchiyun.protocol.netty.dtu.handler.impl;

import cn.dianchiyun.protocol.netty.dtu.entity.DTUWrite;
import cn.dianchiyun.protocol.netty.utils.ConvertCode;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.SocketChannel;
import org.apache.commons.lang.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class StringServerHandler extends ChannelHandlerAdapter {

    private static final Logger logger = LogManager.getLogger("dtu_server");

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        SocketChannel channel = (SocketChannel) ctx.channel();
        System.out.println("链接报告开始 {公众号：bugstack虫洞栈 >获取学习源码}");
        System.out.println("链接报告信息：有一客户端链接到本服务端");
        System.out.println("链接报告IP:" + channel.localAddress().getHostString());
        System.out.println("链接报告Port:" + channel.localAddress().getPort());
        System.out.println("链接报告完毕");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        String dturead = (String) msg;
        System.out.println(dturead);
    }

    /**
     * 公用回写数据到客户端的方法
     *
     * @param dtuWrite 需要回写的字符串
     * @param channel
     * @param mark       用于打印/log的输出
     *                   <br>//channel.writeAndFlush(msg);//不行
     *                   <br>//channel.writeAndFlush(receiveStr.getBytes());//不行
     *                   <br>在netty里，进出的都是ByteBuf，楼主应确定服务端是否有对应的编码器，将字符串转化为ByteBuf
     */
    private void writeToClient(final DTUWrite dtuWrite, ChannelHandlerContext channel, final String mark) {
        try {
            String receiveStr = dtuWrite.getCRCString();
            ByteBuf buf = Unpooled.buffer();//netty需要用ByteBuf传输
            buf.writeBytes(ConvertCode.hexString2Bytes(receiveStr)); //对接需要16进制
            channel.writeAndFlush(dtuWrite).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    StringBuilder sb = new StringBuilder("");
                    if (!StringUtils.isEmpty(mark)) {
                        sb.append("【").append(mark).append("】");
                    }
                    if (future.isSuccess()) {
                        System.out.println(sb.toString() + "回写成功" + receiveStr);
                        logger.info(sb.toString() + "回写成功" + receiveStr);
                    } else {
                        System.out.println(sb.toString() + "回写失败" + receiveStr);
                        logger.error(sb.toString() + "回写失败" + receiveStr);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("调用通用writeToClient()异常" + e.getMessage());
            logger.error("调用通用writeToClient()异常：", e);
        }
    }

}